package main

import (
	"context"
	"fmt"
	"log"
	"net"
	"strconv"

	"learn-go-demo/pkg/config"
	"learn-go-demo/pkg/database"
	"learn-go-demo/pkg/discovery"
	httpHandler "learn-go-demo/pkg/http"
	"learn-go-demo/pkg/models"
	pb "learn-go-demo/proto"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type UserServer struct {
	pb.UnimplementedUserServiceServer
	userRepo *models.UserRepository
}

func (s *UserServer) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.GetUserResponse, error) {
	user, err := s.userRepo.GetByID(int64(req.Id))
	if err != nil {
		log.Printf("Failed to get user: %v", err)
		return nil, status.Errorf(codes.NotFound, "User not found")
	}

	return &pb.GetUserResponse{
		Id:    int32(user.ID),
		Name:  user.Name,
		Email: user.Email,
	}, nil
}

func (s *UserServer) CreateUser(ctx context.Context, req *pb.CreateUserRequest) (*pb.CreateUserResponse, error) {
	user := &models.User{
		Name:  req.Name,
		Email: req.Email,
	}

	err := s.userRepo.Create(user)
	if err != nil {
		log.Printf("Failed to create user: %v", err)
		return nil, status.Errorf(codes.Internal, "Failed to create user")
	}

	return &pb.CreateUserResponse{
		Id:      int32(user.ID),
		Message: "User created successfully",
	}, nil
}

func main() {
	// 加载配置
	cfg, err := config.LoadConfig("./configs")
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}

	log.Printf("Starting %s v%s in %s mode", cfg.App.Name, cfg.App.Version, cfg.App.Environment)

	// 初始化数据库连接
	db, err := database.NewMySQLConnection(cfg.Database)
	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}
	defer db.Close()

	// 初始化用户仓库
	userRepo := models.NewUserRepository(db)

	// 创建表（如果不存在）
	if err := userRepo.CreateTable(); err != nil {
		log.Fatalf("Failed to create user table: %v", err)
	}

	grpcPort := fmt.Sprintf(":%d", cfg.GRPC.Port)
	lis, err := net.Listen("tcp", grpcPort)
	if err != nil {
		log.Fatalf("Failed to listen: %v", err)
	}

	registry := discovery.NewServiceRegistry()
	serviceAddr := fmt.Sprintf("localhost:%d", cfg.GRPC.Port)
	err = registry.Register("user-service", serviceAddr, 30)
	if err != nil {
		log.Fatalf("Failed to register service: %v", err)
	}

	// 启动 gRPC 服务器
	s := grpc.NewServer()
	pb.RegisterUserServiceServer(s, &UserServer{userRepo: userRepo})

	// 启动 HTTP 服务器
	go func() {
		router := httpHandler.SetupRouter()
		userHandler := httpHandler.NewUserHandler(userRepo)
		httpHandler.SetupUserRoutes(router, userHandler)

		httpPort := strconv.Itoa(cfg.HTTP.Port)
		log.Printf("User HTTP server starting on :%s", httpPort)
		httpHandler.StartServer(router, httpPort)
	}()

	log.Printf("User gRPC service starting on %s", grpcPort)
	if err := s.Serve(lis); err != nil {
		log.Fatalf("Failed to serve: %v", err)
	}
}
